package com.argrace.smart.activity.devicerelation;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.activity.DeviceModifyActivity;
import com.argrace.smart.activity.QingJingListActivity;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.entity.Key_ValueEntity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.glide.GliderImageLoaderUtil;
import com.argrace.smart.model.LocalDb_RelationDeviceTable;
import com.argrace.smart.util.AlinkHttpUtil;
import com.zhouyou.view.seekbar.SignSeekBar;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by argrace_dev_1 on 2018/3/6.
 */

public class DeviceRelation_PM25Activity extends BaseActivity {
    private SignSeekBar seekBar_shidu, seekBar_wendu, seekBar_zhishu, seekBar_tvoc;
    private TextView shidu_text, wendu_text, zhishudu_text, tvoc_text;
    MineZigBeeDeviceListEntity bean;
    private ImageView img;
    //此处开始修改为关联设备增加的属性
    String uuid, model;
    LinearLayout relationdevice_ll;
    TextView relationdevice_text;
    private int qingJingTable_id = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devicecontrol_pm25);
        init();
    }

    private void init() {
        bean = (MineZigBeeDeviceListEntity) getIntent().getSerializableExtra("deviceinfo");
        uuid = bean.getUuid();
        model = bean.getModel();
        setView();
        setTitle(true, false, "添加关联");
        showRight(true, R.mipmap.head_title_tick);
        //点击右上角保存此时设备状态与关联场景
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        getDeviceDetailInfo();
    }

    private void save() {
        LocalDb_RelationDeviceTable relationDeviceTable = new LocalDb_RelationDeviceTable();
        relationDeviceTable.setUuid(uuid);
        relationDeviceTable.setModel(model);
        Map<String, String> trigger_condition = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        sb.append("{");
        if (model.equals(ConstantConfigure.MODEL_PM25CHUANGANQI)) {
            sb.append("\"CurrentHumidity\" :");
            Key_ValueEntity entity_shidu = new Key_ValueEntity();
            entity_shidu.setValue(String.valueOf(seekBar_shidu.getProgress()));
            sb.append(entity_shidu.toString());
            sb.append(",");
            sb.append("\"CurrentTemperature\" :");
            Key_ValueEntity entity_wendu = new Key_ValueEntity();
            entity_wendu.setValue(String.valueOf(seekBar_wendu.getProgress()));
            sb.append(entity_wendu.toString());
            sb.append(",");
            sb.append("\"PM25\" :");
            Key_ValueEntity entity_zhishu = new Key_ValueEntity();
            entity_zhishu.setValue(String.valueOf(seekBar_zhishu.getProgress()));
            sb.append(entity_zhishu.toString());
            sb.append(",");
            sb.append("\"TVOC\" :");
            Key_ValueEntity entity_tvoc = new Key_ValueEntity();
            entity_tvoc.setValue(String.valueOf(seekBar_tvoc.getProgress()));
            sb.append(entity_tvoc.toString());
            sb.append(",");
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_KONGQIHEZI)) {
            sb.append("\"CurrentHumidity\" :");
            Key_ValueEntity entity_shidu = new Key_ValueEntity();
            entity_shidu.setValue(String.valueOf(seekBar_shidu.getProgress()));
            sb.append(entity_shidu.toString());
            sb.append(",");
            sb.append("\"CurrentTemperature\" :");
            Key_ValueEntity entity_wendu = new Key_ValueEntity();
            entity_wendu.setValue(String.valueOf(seekBar_wendu.getProgress()));
            sb.append(entity_wendu.toString());
            sb.append(",");
            sb.append("\"PM25\" :");
            Key_ValueEntity entity_zhishu = new Key_ValueEntity();
            entity_zhishu.setValue(String.valueOf(seekBar_zhishu.getProgress()));
            sb.append(entity_zhishu.toString());
            sb.append(",");
            sb.append("\"BatteryPercentage\" :");
            Key_ValueEntity entity_tvoc = new Key_ValueEntity();
            entity_tvoc.setValue(String.valueOf(seekBar_tvoc.getProgress()));
            sb.append(entity_tvoc.toString());
            sb.append(",");
        }
        sb.append("}");
        relationDeviceTable.setTrigger_condition(sb.toString());
        relationDeviceTable.setQingJingTable_id(qingJingTable_id);
        List<LocalDb_RelationDeviceTable> lists = DataSupport.where("uuid = ?", uuid).find(LocalDb_RelationDeviceTable.class);
        Log.i("info", "此时的关联表长度=" + lists.size());
        boolean is_same = false;
        int table_id = 0;
        if (lists != null && lists.size() > 0) {
            for (int i = 0; i < lists.size(); i++) {
                if (lists.get(i).getTrigger_condition() != null && lists.get(i).getTrigger_condition().equals(relationDeviceTable.getTrigger_condition())) {
                    is_same = true;
                    table_id = lists.get(i).getId();
                }
            }
        }
        //如果相等则updata
        if (is_same) {
            relationDeviceTable.update(table_id);
        } else {
            relationDeviceTable.save();
        }
       finish();
        toastActBtm("保存成功");
    }

    private void setView() {
        img = (ImageView) findViewById(R.id.activity_devicecontrol_img);
        String imgurl = null;
        setCanClick(true);
        seekBar_shidu = (SignSeekBar) findViewById(R.id.activity_devicecontrol_pm_shidu);
        seekBar_wendu = (SignSeekBar) findViewById(R.id.activity_devicecontrol_pm_wendu);
        seekBar_zhishu = (SignSeekBar) findViewById(R.id.activity_devicecontrol_pm_zhishu);
        seekBar_tvoc = (SignSeekBar) findViewById(R.id.activity_devicecontrol_pm_tvoc);
        shidu_text = (TextView) findViewById(R.id.activity_devicecontrol_pm_shidu_text);
        wendu_text = (TextView) findViewById(R.id.activity_devicecontrol_pm_wendu_text);
        zhishudu_text = (TextView) findViewById(R.id.activity_devicecontrol_pm_zhishu_text);
        tvoc_text = (TextView) findViewById(R.id.activity_devicecontrol_pm_tvoc_text);
        //modify for relationdevice start
        relationdevice_ll = (LinearLayout) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_ll);
        relationdevice_text = (TextView) findViewById(R.id.activity_devicecontrol_baojing_relationdevice_text);
        relationdevice_ll.setVisibility(View.VISIBLE);
        relationdevice_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeviceRelation_PM25Activity.this, QingJingListActivity.class);
                startActivityForResult(intent, ConstantConfigure.DEFAULT_ZERO);
            }
        });
        //modify for relationdevice end

        if (bean.getModel().equals(ConstantConfigure.MODEL_PM25CHUANGANQI)) {
            shidu_text.setText("当前湿度");
            wendu_text.setText("当前温度");
            zhishudu_text.setText("PM2.5指数");
            tvoc_text.setText("TVOC/VOC浓度");
            imgurl = ConstantConfigure.IMGURL_PM25CHUANGANQI_00011e0f;
            seekBar_shidu.getConfigBuilder()
//                .min(0)
//                .max(4)
//                .progress(2)
//                .sectionCount(4)
//                .thumbColor(ContextCompat.getColor(getContext(), R.color.color_60))
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("%")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekBar_wendu.getConfigBuilder()
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("℃")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekBar_zhishu.getConfigBuilder()
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("μg/m³")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekBar_tvoc.getConfigBuilder()
                    .min(0)
                    .max(10)
                    .progress(2)
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("mg/m³")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_KONGQIHEZI)) {
            shidu_text.setText("当前湿度");
            wendu_text.setText("当前温度");
            zhishudu_text.setText("PM2.5指数");
            tvoc_text.setText("当前电量");
            imgurl = ConstantConfigure.IMGURL_KONGQIHEZI_00011e7e;
            seekBar_shidu.getConfigBuilder()
//                .min(0)
//                .max(4)
//                .progress(2)
//                .sectionCount(4)
//                .thumbColor(ContextCompat.getColor(getContext(), R.color.color_60))
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("%")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekBar_wendu.getConfigBuilder()
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("℃")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekBar_zhishu.getConfigBuilder()
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("μg/m³")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
            seekBar_tvoc.getConfigBuilder()
                    .min(0)
                    .max(100)
                    .progress(2)
                    .sectionTextColor(ContextCompat.getColor(DeviceRelation_PM25Activity.this, R.color.colorPrimary))
                    .sectionTextSize(15)
                    .setUnit("%")//setUnit("μmol/l");setUnit("μ/l") setUnit("m")
                    .build();
        }
        if (imgurl != null) {
            GliderImageLoaderUtil.load(this, imgurl, img);
        }

    }

    //查询设备最新状态
    private void getDeviceDetailInfo() {
        String method = "mtop.openalink.app.core.device.get.status";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", bean.getUuid());
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                if (transitoryResponse == null || transitoryResponse.data == null) {
                    return;
                }
                Log.i("info", "子设备最新状态成功" + transitoryResponse.data);
                JSONObject obj = JSON.parseObject(transitoryResponse.data.toString());
                fillData(obj, obj.getString("uuid"));
            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Log.i("info", "子设备最新状态失败" + aError.getMsg() + aError.getCode());
            }
        });
    }

    private void fillData(JSONObject obj, String uuid) {
        if (uuid == null || !uuid.equals(bean.getUuid())) {
            return;
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_PM25CHUANGANQI)) {
            Key_ValueEntity currentHumidity = JSON.parseObject(obj.getString("CurrentHumidity"), Key_ValueEntity.class);
            Key_ValueEntity currentTemperature = JSON.parseObject(obj.getString("CurrentTemperature"), Key_ValueEntity.class);
            Key_ValueEntity pM25 = JSON.parseObject(obj.getString("PM25"), Key_ValueEntity.class);
            Key_ValueEntity tVOC = JSON.parseObject(obj.getString("TVOC"), Key_ValueEntity.class);
            float progress_shidu = (float) Double.parseDouble(currentHumidity.getValue());
            float progress_wendu = (float) Double.parseDouble(currentTemperature.getValue());
            float progress_zhishu = (float) Double.parseDouble(pM25.getValue());
            float progress_tvoc = (float) Double.parseDouble(tVOC.getValue());
            seekBar_shidu.setProgress(progress_shidu);
            seekBar_wendu.setProgress(progress_wendu);
            seekBar_zhishu.setProgress(progress_zhishu);
            seekBar_tvoc.setProgress(progress_tvoc);
        }
        if (bean.getModel().equals(ConstantConfigure.MODEL_KONGQIHEZI)) {
            Key_ValueEntity currentHumidity = JSON.parseObject(obj.getString("CurrentHumidity"), Key_ValueEntity.class);
            Key_ValueEntity currentTemperature = JSON.parseObject(obj.getString("CurrentTemperature"), Key_ValueEntity.class);
            Key_ValueEntity pM25 = JSON.parseObject(obj.getString("PM25"), Key_ValueEntity.class);
            Key_ValueEntity tVOC = JSON.parseObject(obj.getString("BatteryPercentage"), Key_ValueEntity.class);
            float progress_shidu = (float) Double.parseDouble(currentHumidity.getValue());
            float progress_wendu = (float) Double.parseDouble(currentTemperature.getValue());
            float progress_zhishu = (float) Double.parseDouble(pM25.getValue());
            float progress_tvoc = (float) Double.parseDouble(tVOC.getValue());
            seekBar_shidu.setProgress(progress_shidu);
            seekBar_wendu.setProgress(progress_wendu);
            seekBar_zhishu.setProgress(progress_zhishu);
            seekBar_tvoc.setProgress(progress_tvoc);
        }
    }

    private void setCanClick(boolean value) {
        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
        if (value) {
        } else {
            ll.setOnClickListener(null);
            ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toastActBtm("不可点击");
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String name = data.getStringExtra("name");
            qingJingTable_id = data.getIntExtra("id", 0);
            relationdevice_text.setText(name);
        }
    }

}

